#pragma ocne

#include <iostream>
#include <string>
#include <vector>
#include <sqlite3.h>

class SqliteHelper
{
public:
    using sqlite_cb = int (*)(void*, int, char**,char**);
public:
    SqliteHelper(const std::string& dbfile): _dbfile(dbfile), _handler(nullptr)
    {}

    bool open(int safeLevel = SQLITE_OPEN_FULLMUTEX) //安全等级：串行化（满锁）
    {
        // int sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs );
        int ret = sqlite3_open_v2(_dbfile.c_str(), &_handler, SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE|safeLevel, nullptr);
        if(ret != SQLITE_OK)
        {
            std::cout << "sqlite open failed: " << sqlite3_errmsg(_handler) << std::endl;
            return false;
        }
        return true;
    }

    bool execute(const std::string& sql, sqlite_cb cb, void* arg) //sql语句，回调函数，回调函数参数
    {
        // int sqlite3_exec(sqlite3*, char *sql, int (*callback)(void*,int,char**,char**), void* arg, char **err);
        int ret = sqlite3_exec(_handler, sql.c_str(), cb, arg, nullptr);
        if(ret != SQLITE_OK)
        {
            std::cout << "sqlite execute failed: " << sqlite3_errmsg(_handler) << std::endl;
            return false;
        }
        return true;
    }

    void close()
    {
        // int sqlite3_close_v2(sqlite3*);
        if(_handler) sqlite3_close_v2(_handler);
    }

    ~SqliteHelper()
    {}
private:
    std::string _dbfile;
    sqlite3* _handler;
};